package com.vonzhou.spitter.service;

import com.vonzhou.spitter.common.Spitter;
import com.vonzhou.spitter.common.Spittle;
import com.vonzhou.spitter.persistence.SpitterDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static java.lang.Math.min;
import static java.util.Collections.reverse;


@Component("spitterService")
@Transactional(propagation = Propagation.REQUIRED)
public class SpitterServiceImpl implements SpitterService {

	@Autowired
	SpitterDao spitterDao;

	@Override
	public void saveSpitter(Spitter spitter) {
		if (spitter.getId() == null) {
			spitterDao.addSpitter(spitter);
		} else {
			spitterDao.saveSpitter(spitter);
		}

		//throw new HibernateException("Simulate Error Oops..");
	}

	@Override
	public void saveSpittle(Spittle spittle) {
		spitterDao.saveSpittle(spittle);
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public List<Spittle> getRecentSpittles(int count) {
		List<Spittle> recentSpittles =
				spitterDao.getRecentSpittle();

		reverse(recentSpittles);

		return recentSpittles.subList(0,
				min(49, recentSpittles.size()));
	}

	@Override
	public Spitter getSpitter(long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void startFollowing(Spitter follower, Spitter followee) {
		// TODO Auto-generated method stub

	}

	@Override
	public Spitter getSpitter(String username) {
		return spitterDao.getSpitterByUsername(username);
	}

	@Override
	public List<Spittle> getSpittlesForSpitter(Spitter spitter) {
		return spitterDao.getSpittlesForSpitter(spitter);
	}

	@Override
	public List<Spittle> getSpittlesForSpitter(String username) {
		Spitter spitter = spitterDao.getSpitterByUsername(username);
		return getSpittlesForSpitter(spitter);
	}

	@Override
	public List<Spitter> getAllSpitters() {
		return spitterDao.findAllSpitters();
	}

	@Override
	public void deleteSpittle(long id) {
		spitterDao.deleteSpittle(id);
	}

	@Override
	public Spittle getSpittleById(long id) {
		return spitterDao.getSpittleById(id);
	}
}
